<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动主题" prop="activityTheme">
        <el-input v-model="queryParams.activityTheme" placeholder="请输入活动主题" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="报名人" prop="applicant">
        <el-input v-model="queryParams.applicant" placeholder="请输入报名人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="报名时间" prop="registrationTime">
        <el-date-picker clearable v-model="queryParams.registrationTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择报名时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <!-- <el-input v-model="queryParams.auditStatus" placeholder="请输入报名人" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" @change="handleQuery">
          <el-option v-for="item in optionsAudit" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['staff:OneStopRegistrationRecord:add']">新增</el-button>
      </el-col> -->
      <div style="display: flex; align-items: center;justify-content: space-between;">
        <div style="display: flex; align-items: center;">
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple" v-if="queryParams.auditStatus == 0"
              @click="handleBatchUpdate('同意')" v-hasPermi="['staff:OneStopRegistrationRecord:edit']">批量同意</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" v-if="queryParams.auditStatus == 0"
              @click="handleBatchUpdate('不同意')"
              v-hasPermi="['staff:OneStopRegistrationRecord:remove']">批量不同意</el-button>
          </el-col>
          <el-col :span="1.5">
            <div style="font-size: 14px;">
              当前显示的是<span style="color: red; font-size: 14px; font-weight: bold;">{{
                switchAuditStatus(queryParams.auditStatus) }}</span>的报名记录
            </div>
          </el-col>
        </div>
        <div>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="OneStopRegistrationRecordList" @selection-change="handleSelectionChange" :default-sort = "{prop: 'registrationTime', order: 'descending'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动主题" align="center" prop="activityTheme" />
      <el-table-column label="发起人" align="center" prop="initiator" />
      <el-table-column label="报名人" align="center" prop="applicant" />
      <el-table-column label="报名时间" align="center" prop="registrationTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ scope.row.registrationTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.auditStatus === 0">待审核</el-tag>
          <el-tag type="success" v-else-if="scope.row.auditStatus === 1">通过</el-tag>
          <el-tag type="danger" v-else>不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row, '审核')"
            v-if="scope.row.auditStatus === 0" v-hasPermi="['staff:OneStopRegistrationRecord:edit']">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row, '详情')" v-else
            v-hasPermi="['staff:OneStopRegistrationRecord:edit']">详情</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['staff:OneStopRegistrationRecord:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改一站式社区模块-社区活动-报名记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="社区活动" prop="activityId">
          <el-select v-model="form.activityId" placeholder="请选择社区活动" style="width: 100%;" @change="activityChange">
            <el-option v-for="item in activityList" :key="item.activityId" :label="item.activityTheme"
              :value="item.activityId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动主题" prop="activityTheme">
          <el-input v-model="form.activityTheme" placeholder="请输入活动主题" disabled />
        </el-form-item>
        <el-form-item label="发起人" prop="initiator">
          <el-input v-model="form.initiator" placeholder="请输入发起人" disabled />
        </el-form-item>
        <el-form-item label="报名人" prop="applicant">
          <el-input v-model="form.applicant" placeholder="请输入报名人" />
        </el-form-item>
        <el-form-item label="报名时间" prop="registrationTime">
          <el-date-picker clearable v-model="form.registrationTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;" placeholder="请选择报名时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog :title="handleAuditTitle" :visible.sync="openAudit" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="handleAuditTitle === '审核'">
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="form.auditStatus">
            <el-radio :label="0" disabled>待审核</el-radio>
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div v-else>
        <div v-if="handleAuditTitle !== null">
          <el-result :icon="`${form.auditStatus === 1 ? 'success' : 'error'}`"
            :title="`${form.auditStatus === 1 ? '报名成功' : '报名失败'}`" subTitle="请根据提示进行操作">
          </el-result>
          <div v-if="form.auditStatus === 1">
            <p style="font-weight: bold;">请你于{{ form.communityActivitiesList[0].activityTime | formatDate }}，上午{{
              handleTimeHours(form)
            }}点前，到{{ form.communityActivitiesList[0].activityPlace }}集合，不允许迟到</p>
            <p style="margin-top: 20px;">报名信息</p>
            <p>报名人：{{ form.applicant }}</p>
            <p>报名时间：{{ form.registrationTime || '暂无填写'}}</p>
            <p>活动主题：{{ form.activityTheme || '暂无填写' }}</p>
            <p>时间：{{ form.registrationTime || '暂无填写' }}</p>
            <p>地点：{{ form.communityActivitiesList[0].activityPlace || '暂无填写' }}</p>
            <p>人数：{{ form.communityActivitiesList[0].galleryful || '暂无填写' }}人</p>
            <p>具体要求：</p>
            <p>{{ form.communityActivitiesList[0].specificRequirements || '暂无填写' }}</p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" v-if="handleAuditTitle === '审核'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOneStopRegistrationRecord, getOneStopRegistrationRecord, delOneStopRegistrationRecord, addOneStopRegistrationRecord, updateOneStopRegistrationRecord, batchUpdateSysRegistrationRecord } from "@/api/staff/OneStopRegistrationRecord";
import { listAll } from "@/api/staff/OneStopCommunityActivities";
export default {
  name: "OneStopRegistrationRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 一站式社区模块-社区活动-报名记录表格数据
      OneStopRegistrationRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openAudit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityId: null,
        activityTheme: null,
        initiator: null,
        applicant: null,
        registrationTime: null,
        auditStatus: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityId: [
          { required: true, message: "社区活动id不能为空", trigger: "blur" }
        ],
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" }
        ],
      },
      activityList: [],
      handleAuditTitle: null,
      batchRecordList: [],
      optionsAudit: [ // 下拉选项数组
        { value: null, label: '全部' },
        { value: 0, label: '待审核' },
        { value: 1, label: '同意' },
        { value: 2, label: '不同意' }
      ]
    };
  },
  watch: {
    "$route.query.activityId": {
      immediate: true,
      handler() {
        this.queryParams.activityId = null
        this.reset()
        if (this.$route.query.activityId !== undefined) {
          if (this.$route.query.activityId !== null) {
            this.queryParams.activityId = this.$route.query.activityId
            return
          }
          this.queryParams.activityId = null
          this.queryParams.auditStatus = null
          this.reset()
        } else {
          this.queryParams.activityId = null
          this.queryParams.auditStatus = null
          this.getList()
          this.reset()
        }
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询一站式社区模块-社区活动-报名记录列表 */
    getList() {
      this.loading = true;
      listOneStopRegistrationRecord(this.queryParams).then(response => {
        this.OneStopRegistrationRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listAll().then(response => {
        this.activityList = response.data
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAudit = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        activityId: null,
        activityTheme: null,
        initiator: null,
        applicant: null,
        registrationTime: null,
        auditStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.batchRecordList = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加一站式社区模块-社区活动-报名记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getOneStopRegistrationRecord(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改一站式社区模块-社区活动-报名记录";
      });
    },
    activityChange() {
      let data = this.activityList.filter(item => item.activityId == this.form.activityId)
      if (data.length > 0) {
        this.form.activityTheme = data[0].activityTheme; // 将第一个元素的activityTheme赋值给this.form.activityTheme
        this.form.initiator = data[0].eventPromoter
      } else {
        console.log("没有找到匹配的活动");
        // 可以在这里处理没有找到匹配活动的情况
      }
    },
    // 打开审核对话框
    handleAudit(row, text) {
      this.openAudit = true
      let data = JSON.stringify(row)
      this.form = JSON.parse(data)
      this.handleAuditTitle = text
    },
    handleTimeHours(row) {
      // 首先，将字符串转换为Date对象
      // 注意：在大多数现代浏览器中，这种格式的字符串可以直接被Date构造函数解析
      let hours = ""
      if (row.communityActivitiesList[0].activityTime != undefined) {
        let dateTime = new Date(row.communityActivitiesList[0].activityTime);
        // 然后，使用getHours()方法来获取小时
        hours = dateTime.getHours();
      }
      return hours
    },
    /** 提交按钮 */
    submitForm() {
      this.$modal.loading("正在努力加载中，请稍等。。。");
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查表单中是否有空字符串
          let hasEmptyString = Object.values(this.form).some(value => {
            return (value !== null && value !== undefined && (typeof value === 'string' ? value.trim() === '' : false));
          });

          if (hasEmptyString) {
            this.$modal.msgError("表单中存在空字符串，请填写完整");
            return;
          }
          if (this.form.recordId != null) {
            updateOneStopRegistrationRecord(this.form).then(response => {
              this.$modal.msgSuccess("审核成功");
              this.open = false;
              this.openAudit = false;
              this.getList();
              this.$modal.closeLoading();
            });
          } else {
            addOneStopRegistrationRecord(this.form).then(response => {
              if (response.code !== 500) {
                this.$modal.msgSuccess("新增成功");
                this.getList();
              }
              this.open = false;
              this.$modal.closeLoading();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除一站式社区模块-社区活动-报名记录编号为"' + recordIds + '"的数据项？').then(function () {
        return delOneStopRegistrationRecord(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('staff/OneStopRegistrationRecord/export', {
        ...this.queryParams
      }, `活动报名记录_${new Date().getTime()}.xlsx`)
    },
    // 批量审核
    handleBatchUpdate(text) {
      this.$confirm('此操作将审核该报名记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading("正在努力加载中，请稍等。。。");
        let auditStatus = text === '同意' ? 1 : 2
        this.batchRecordList.forEach(element => {
          element.auditStatus = auditStatus
        });
        batchUpdateSysRegistrationRecord(this.batchRecordList).then(() => {
          this.$modal.msgSuccess("审核成功");
          this.$modal.closeLoading();
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审核'
        });
      });
    },
    switchAuditStatus(status) {
      return this.optionsAudit.filter(item => item.value === status)[0].label
    }
  }
};
</script>
